<?php

namespace App\Service;

use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Database\Transaction\Transaction;
use function App\Controller\generateSHA256;

class KsApiService extends CommicService
{
    public function get_access_token(string $applet_id ){
        $key = 'ks_access_token';
        $key .= $applet_id;
        $access_token = $this->redisService->get($key);
        if(empty($access_token) || true) {
            $applet_info = $this->get_applet_info($applet_id);
            $url_url = "https://open.kuaishou.com/oauth2/access_token";
            $postData = [
                'app_id' => $applet_info['app_id'],
                'app_secret' => $applet_info['app_secret'],
                'grant_type' => 'client_credentials'
            ];
            $headers = [
                'content-type' => 'application/x-www-form-urlencoded',
            ];
            // 将数组进行URL编码
            $postData = http_build_query($postData);

            $response = $this->httpclient->post($url_url, [
                'headers' => $headers,
                'body' => $postData
            ]);
            $content = $response->getBody()->getContents();
            $res = json_decode($content, true);
            if (!empty($res["access_token"])){
                $access_token = $res["access_token"];
                $this->redisService->Set($key,$access_token);
                #有效期48小时,
                $this->redisService->expire($key,171000);
            }else{
                $access_token = "";
            }
            return  $access_token;
        }
    }
    public function  create_order(string $applet_id,string $open_id,string $out_order_no,int $amount){
        $applet_info = $this->get_applet_info($applet_id);
        $appid = $applet_info['app_id'];
        $access_token = $this->get_access_token($applet_id);
        $url_url = "https://open.kuaishou.com/openapi/mp/developer/epay/create_order?access_token={$access_token}&app_id={$appid}";
        $postData = [
            'app_id' =>$appid,
            'open_id' => $open_id,
            'out_order_no' => $out_order_no,
            'total_amount' => $amount,
            'attach' => $applet_id,
            'subject' => "充值",
            'type' => 1273,
            'detail' => "短剧充值",
            'expire_time' => 3600,
            'notify_url' => "https://tests.kuaiyingbox.com/uwx/check_signature",
        ];
        $sign = $this->get_sign($applet_id,$postData);
        $postData['sign'] = $sign;
        unset($postData['app_id']);
        $headers = [
            'content-type' => 'application/json',
        ];
        $response = $this->httpclient->post($url_url, [
            'headers' => $headers,
            'json' => $postData
        ]);
        $content = $response->getBody()->getContents();
        $res = json_decode($content, true);
        if($res['result'] == 1) {
            return $res['order_info'];
        } else {
            return  0;
        }
    }
    public  function get_sign($applet_id,$signParamsMap) {
        $applet_info = $this->get_applet_info($applet_id);
        // 去掉 value 为空的
        $trimmedParamMap = array_filter($signParamsMap, function($value) {
            return !empty($value);
        });
        // 按照字母排序
        ksort($trimmedParamMap);

        // 组装成待签名字符串
//        $paramStr = http_build_query($trimmedParamMap, '', '&');
        $paramStr = '';
        foreach ($trimmedParamMap as $key=>$value) {
            $paramStr .= $key.'=' .$value .'&';
        }
        $paramStr =  rtrim($paramStr,'&');
        $signStr = $paramStr . $applet_info['app_secret'];
        // 生成签名返回
        return md5($signStr);
    }

    public function get_decrypt_sign($applet_id,$signParamsMap,$signature)
    {
        $applet_info = $this->get_applet_info($applet_id);

        $toSignStr = $signParamsMap . $applet_info['app_secret'];

        $sign = md5($toSignStr);

        $result = ($sign === $signature);

        return (bool)$result;

    }
}